import 'package:barcode_scan/barcode_scan.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class ScanPage extends StatefulWidget{

  @override
  State<StatefulWidget> createState() => _ScanState();

}

class _ScanState extends State<ScanPage> {

  String log = "操作结果：\n";

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text('扫一扫'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            CupertinoButton(
              color: Colors.blue,
              child: Text('扫一扫'),
              onPressed: scan,
            ),
            Padding(
              padding: EdgeInsets.only(top: 20.0),
              child: Text(log),
            )
          ],
        ),
      ),
    );
  }

  Future scan() async {
    try{
      String barcode = await BarcodeScanner.scan();
      log += '扫码结果：$barcode\n';
    } on PlatformException catch (e) {
      if(e.code == BarcodeScanner.CameraAccessDenied) {
        log += '未授予App相机权限\n';
      } else {
        log += '扫码错误：$e\n';
      }
    } on FormatException {
      log += '进入扫码页面后未扫码就返回\n';
    } catch (e) {
      log += '扫码错误: $e\n';
    }
    setState(() {});
  }

}